//
//  HSCDViewController.m
//  NursingManage
//
//  Created by Zhen Huang on 17/5/12.
//  Copyright © 2017年 yzm. All rights reserved.
//

#import "HSCDViewController.h"
#import "SCDMODEL.h"
#import "Networking.h"
#import <FMDB.h>
#import "FMDBModel.h"
#import "Model_Hr_Scheduling.h"
#import "SizeToFit.h"
#import "InitDbTable.h"
#import "TabelSCD.h"
#import "UserDefault.h"
#define calright(m,r) m.superview.frame.size.width -  m.frame.size.width - r

@interface HSCDViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    
    UICollectionView *_collectionV;
    NSMutableArray *dataSourceArr;
    NSArray  *_weekDayArray;
}
@property (nonatomic, strong) NSMutableArray* bodyViewAry;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) id myself;
@property (nonatomic, strong) Model_Hr_Scheduling *curdate;
@property (nonatomic, strong) UIView *lineHB;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UILabel *datelabel;
@property (nonatomic, strong) UILabel *SCDlabel;
@property (nonatomic, strong) NSMutableArray *bigArray;
@property (nonatomic, strong) NSMutableArray *BigArray;
@property (nonatomic, strong) UILabel *content;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *dateArray;
@property (nonatomic, strong) NSMutableArray *classArray;
@property (nonatomic, strong) NSMutableDictionary *monthDic;
@property (nonatomic, strong) UILabel *WorkLabel;
@property (nonatomic, copy) NSString *contentString;
@property (nonatomic, copy) NSString *yearMonths;
@property (nonatomic, copy) NSString *natitle;
@property (nonatomic, copy) NSString *URLs;
@property (nonatomic, copy) NSString *String;
@property (nonatomic, copy) NSString *COUNT;
@property (nonatomic, copy) NSString *COUNT1;
@property (nonatomic, copy) NSString *modelDate;
@property (nonatomic, copy) NSString *YearMonth;
@property (nonatomic, copy) NSString *dateString;
@property (nonatomic, copy) NSString *yearMonth;
@property (nonatomic, assign) BOOL did;

@end

@implementation HSCDViewController
- (instancetype)initWithTitle:(NSString *)titles {
    if (self = [super init]) {
        self.dataArray = [NSMutableArray new];
        self.classArray = [NSMutableArray new];
        self.bodyViewAry = [NSMutableArray new];
        self.bigArray = [NSMutableArray new];
        self.BigArray= [NSMutableArray new];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

    // Do any additional setup after loading the view.
}
#pragma remark -赋值日期结构体
- (void)setACurDate:(NSDate*)date{
    if(date){
        _curdate.date = date;
        _curdate.yearMonth =[self getYearMonth:date];
    }
}

#pragma remark -创建页面
- (void)createHeaderView{
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, ScreenHeight+20 )];
    _headerView.backgroundColor = [UIColor whiteColor];
    
    UIButton *prevbtnBefore = [UIButton buttonWithType:UIButtonTypeCustom];
    prevbtnBefore.top=20;
    prevbtnBefore.height =22.5;
    prevbtnBefore.width =25;
    [prevbtnBefore setImage:[UIImage imageNamed:@"icon_left2"] forState:UIControlStateNormal];
    [prevbtnBefore addTarget:self action:@selector(beforebtn:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *prevbtnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    prevbtnBack.top=20;
    prevbtnBack.height = 22.5;
    prevbtnBack.width = 25;
    [prevbtnBack setImage:[UIImage imageNamed:@"icon_rightSC"] forState:UIControlStateNormal];
    [prevbtnBack addTarget:self action:@selector(backbtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView* lineHT = [[UIView alloc] init];
    lineHT.width = ScreenWidth;
    lineHT.height = 0.5f;
    lineHT.backgroundColor = RGB(212, 212, 212);
    lineHT.top=70;
    
    UIView* weekView = [[UIView alloc]init];
    weekView.width = ScreenWidth;
    weekView.height = 20;
    weekView.top = lineHT.bottom;
    [self createContentHeaderView:weekView];
    
    _lineHB = [[UIView alloc] init];
    _lineHB.width = ScreenWidth;
    _lineHB.height = 0.5f;
    _lineHB.backgroundColor = RGB(212, 212, 212);
    _lineHB.top=weekView.bottom;
    
    [self createContentBodyView:_headerView];
    [_headerView addSubview:lineHT];
    [_headerView addSubview:_lineHB];
    [_headerView addSubview:weekView];
    [_headerView addSubview:prevbtnBefore];
    [_headerView addSubview:prevbtnBack];
    [_headerView addSubview:self.datelabel];
    prevbtnBefore.left=  calright(prevbtnBefore,70);
    prevbtnBack.left=  calright(prevbtnBack,20);
}

-(void)createContentHeaderView:(UIView*)baseView{
    CGSize size = baseView.frame.size;
    CGFloat linewidth = 0.5f;
    CGFloat lbwidth = (size.width - linewidth*6) / 7;
    
    for (int i=0; i<7; i++) {
        UILabel* label = [[UILabel alloc]init];
        label.width = lbwidth;
        label.height = size.height;
        label.left = i*(lbwidth+linewidth);
        label.text =  [[_myself getWeekName:i] substringFromIndex:2];
        label.textAlignment = NSTextAlignmentCenter;
        if(i<1 || i > 5){
            label.textColor = [UIColor redColor];
        }
        if(i!=6){
            UIView* vertical = [[UIView alloc] initWithFrame:CGRectMake( (i+1)*lbwidth+i*linewidth, 0, linewidth, size.height)];
            vertical.backgroundColor = RGB(212, 212, 212);
            [baseView addSubview:vertical];
            vertical.backgroundColor= RGB(212, 212, 212);
        }
        
        [baseView addSubview:label];
    }
}

-(void)createContentBodyView:(UIView*)baseView{
    for (UIView* v in self.bodyViewAry) {
        [v removeFromSuperview];
    }
    [_bodyViewAry removeAllObjects];
    NSInteger startdays = [self getMonthFirstDayIsWeekDay:_curdate.date];
    NSDate* nowMonthFD = [self getMonthFirstDay:_curdate.date];
    NSDate* nextMonthFD = [self addMonths:nowMonthFD WithMonth:1];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned int unitFlags = NSCalendarUnitDay;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:nowMonthFD toDate:nextMonthFD options:0];
    NSInteger monthAllDays = [comps day];//时间差
    
    long totol = monthAllDays + startdays;
    long alltotal = totol;
    
    int tys =totol %7;
    if(tys != 0){
        alltotal = alltotal + 7 - tys;
    }
    UIView *rowView = nil;
    UIView *preview = nil;
    UIView *line = nil;
    
    CGSize size = baseView.frame.size;
    CGFloat linewidth = 0.5f;
    CGFloat colwidth = (size.width - linewidth*6) / 7;
    for (int d = 0; d<alltotal; d++) {
        int ys = d%7;
        
        if(ys == 0){
            if(line) {
                preview = line;
            }
            else {
                preview = _lineHB;
            }
            rowView = [[UIView alloc]init];
            rowView.width = baseView.frame.size.width;
            rowView.height = 35;
            rowView.top = preview.bottom+5 ;
            //横线的颜色
            line = [[UIView alloc] init];
            line.backgroundColor = RGB(212, 212, 212);
            line.width = ScreenWidth;
            line.height = 0.5f;
            line.top=rowView.bottom+40;
            
            [_bodyViewAry addObject:rowView];
            [_bodyViewAry addObject:line];
            
            [baseView addSubview:rowView];
            [baseView addSubview:line];
        }
        //日历颜色
        UIView* colView = [[UIView alloc]init];
        colView.width = colwidth;
        colView.height = rowView.height;
        colView.left = ys*(colwidth+linewidth);
        
        [rowView addSubview:colView];
        
        if(ys!=6){
            //竖线
            UIView* vertical = [[UIView alloc] initWithFrame:CGRectMake((ys+1)*colwidth+ys*linewidth, -5, linewidth, colView.height + 45)];
            vertical.backgroundColor = RGB(212, 212, 212);
            [rowView addSubview:vertical];
        }
        //日历数字背景颜色
        if(d>=startdays && d <=totol-1){
            self.content = [[UILabel alloc]init];
            self.content.width = colView.width;
            self.content.height=15;
            self.content.textAlignment = NSTextAlignmentCenter;
            self.content.textColor = [UIColor grayColor];
            self.content.font = [UIFont systemFontOfSize:15];
            self.content.text = [NSString stringWithFormat:@"%ld", (long)(d-startdays + 1)];
            [colView addSubview:self.content];
            self.WorkLabel=  [[UILabel alloc]initWithFrame:CGRectMake(0, self.content.height, 30, 70)];
            self.WorkLabel.centerX = self.content.centerX+35;
            [colView addSubview:self.WorkLabel];
            self.WorkLabel.font = [UIFont systemFontOfSize:13];
            self.WorkLabel.numberOfLines = 0;
            self.WorkLabel.textAlignment = NSTextAlignmentCenter;
        }
        NSString *STring = @"";
            if (self.content.text.length < 2) {
            NSString *contents= [NSString stringWithFormat:@"0%@",self.content.text];
            NSString *string = [NSString stringWithFormat:@"%@%@",self.datelabel.text,contents];
            STring= [string stringByReplacingOccurrencesOfString:@"." withString:@""];
        }else {
            NSString *string = [NSString stringWithFormat:@"%@%@",self.datelabel.text,self.content.text];
            STring = [string stringByReplacingOccurrencesOfString:@"." withString:@""];
            
        }
        for (int j = 0; j < self.bigArray.count; j++) {
          Model_Hr_Scheduling *model = self.bigArray[j];
          NSString *string = [model.SCD_DATE stringByReplacingOccurrencesOfString:@"-" withString:@""];
            if ([string isEqualToString:STring]) {
                self.WorkLabel.text = model.CLASS_NAME;
            CGFloat height = [SizeToFit getHeightByWidth:30 title:self.WorkLabel.text font:self.WorkLabel.font];
            self.WorkLabel.frame = CGRectMake(15, self.content.height, 30, height);
            }
        }
    }
}

- (void)beforebtn:(UIButton *)sender {
    self.did = YES;
    NSDate *nowDate = [self addMonths:self.curdate.date WithMonth:-1];
    [self setACurDate:nowDate];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy.MM"];
    self.datelabel.text = [dateFormatter stringFromDate: nowDate];
    
    NSMutableString  *string= [[NSMutableString alloc] initWithString :self.datelabel.text];
    [string insertString:@"-"  atIndex:4];
    
    
    NSDate *nowDate1 = [self addMonths:self.curdate.date WithMonth:1];
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    [dateFormatter1 setDateFormat:@"yyyy.MM"];
    self.COUNT= [dateFormatter1 stringFromDate: nowDate1];
    NSString *sting = [string stringByReplacingOccurrencesOfString:@"." withString:@""];
    self.yearMonths = sting;
    [self createContentBodyView:self.headerView];
    [self.tableView reloadData];
    
}
- (void)backbtn:(UIButton *)sender {
    self.did = YES;
    
    NSDate *nowDate = [self addMonths:self.curdate.date WithMonth:1];
    [self setACurDate:nowDate];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy.MM"];
    self.datelabel.text = [dateFormatter stringFromDate: _curdate.date];
    NSMutableString  *string= [[NSMutableString alloc ] initWithString :self.datelabel.text];
    [string insertString:@"-"  atIndex:4];
    
    NSDate *nowDate1 = [self addMonths:self.curdate.date WithMonth:1];
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    [dateFormatter1 setDateFormat:@"yyyy.MM"];
    self.COUNT= [dateFormatter1 stringFromDate: nowDate1];
    
    NSString *sting = [string stringByReplacingOccurrencesOfString:@"." withString:@""];
    self.yearMonths = sting;
    [self createContentBodyView:self.headerView];
    [self.tableView reloadData];
    
}

#pragma mark -创建headerView
- (void)buildHeaderView:(NSString*)yearMonth {
    
}

#pragma mark -获得当前年月
-(NSString*)getYearMonth:(NSDate*)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    return [dateFormatter stringFromDate: date];
}

#pragma mark -月份的增减
-(NSDate*)addMonths:(NSDate*)nowdate WithMonth:(NSInteger)month{
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    [comps setMonth:month];
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *rDate = [calendar dateByAddingComponents:comps toDate:nowdate options:0];
    return rDate;
}

#pragma mark -该月第一天是星期几
-(NSInteger)getMonthFirstDayIsWeekDay:(NSDate*)date{
    NSDate *monthFirstDay=[self getMonthFirstDay:date];
    NSDateFormatter* weekDaysFormatter = [[NSDateFormatter alloc] init];
    [weekDaysFormatter setDateFormat:@"E"];
    NSString *weekName=[weekDaysFormatter stringFromDate: monthFirstDay];
    return [self getWeekDays:weekName];
}
#pragma mark -该月第一天
-(NSDate*)getMonthFirstDay:(NSDate*)date{
    NSString* yearMonth = [self getYearMonth:date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *monthFirstDay=[dateFormatter dateFromString:[yearMonth stringByAppendingString:@"-01"]];
    return monthFirstDay;
}

#pragma mark -星期几转换成对应数字 0是星期日
-(NSInteger)getWeekDays:(NSString*)weekName{
    if ([weekName isEqualToString:@"周一"]) {
        return 1;
    }else if ([weekName isEqualToString:@"周日"]){
        return 0;
    }else if ([weekName isEqualToString:@"周二"]){
        return 2;
    }else if ([weekName isEqualToString:@"周三"]){
        return 3;
    }else if ([weekName isEqualToString:@"周四"]){
        return 4;
    }else if ([weekName isEqualToString:@"周五"]){
        return 5;
    }else{
        return 6;
    }
}
#pragma mark -数字转换成对应星期几 0是星期日
-(NSString*)getWeekName:(NSInteger)weekDays{
    switch (weekDays) {
        case 0:{
            return  @"星期日";
            
        }
            break;
        case 1:{
            return  @"星期一";
            
        }
            break;
        case 2:{
            return  @"星期二";
            
        }
            break;
        case 3:{
            return  @"星期三";
            
        }
            break;
        case 4:{
            return  @"星期四";
            
        }
            break;
        case 5:{
            return  @"星期五";
            
        }
            break;
        default:{
            return  @"星期六";
            
        }
            break;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
- (void)viewWillAppear:(BOOL)animated
{
    NSString * emp_id = UserDefault.getUserInfo.EMP_ID;
    
    [InitDbTable sharedFMDBManeger];
    NSArray *arrayQ =  [[[TabelSCD alloc]init]allModelSCD:emp_id];
    self.bigArray = (NSMutableArray *)arrayQ;
    [UIView setAnimationsEnabled:YES];
    self.curdate = [[Model_Hr_Scheduling alloc]init];
    self.myself = self;
    self.bodyViewAry = [[NSMutableArray alloc]init];
    self.view .backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor =RGB(13, 140, 236);
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]};
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, ScreenHeight+20)];
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    [self.view addSubview:self.tableView];
    NSDate* nowDate = [NSDate date];
    [self setACurDate:nowDate];
    [self createHeaderView];
    self.tableView.tableHeaderView = self.headerView;
    self.datelabel = [[UILabel alloc]initWithFrame:CGRectMake(20,20, 120, 30)];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy.MM"];
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    [dateFormatter1 setDateFormat:@"yyyy-MM"];
    self.yearMonth = [dateFormatter stringFromDate:nowDate];
    self.YearMonth = [dateFormatter1 stringFromDate:nowDate];
    self.datelabel.text = [dateFormatter stringFromDate: _curdate.date];
    self.datelabel.font = [UIFont systemFontOfSize:24.f];
    [self.headerView addSubview:self.datelabel];
    [self createContentBodyView:self.headerView];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 @end
